<script setup lang="ts">
import { ElDialog } from 'element-plus';
import aeCommands from './component/aeCommands.vue';
import { computed, onMounted, onUnmounted, ref, toRaw, watch } from "vue";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import AefftConfig from "@/views/configs/deviceConfig/component/aefftConfig.vue";
import AefirConfig from "@/views/configs/deviceConfig/component/aeFirConfig.vue";
import Aefrp from "@/views/configs/deviceConfig/component/aeFrp.vue";
import AeLevelConfig from "@/views/configs/deviceConfig/component/aeLevelConfig.vue";
import AeParamConfig from "@/views/configs/deviceConfig/component/aeParamConfig.vue";
import AeTimingConfig from "@/views/configs/deviceConfig/component/aeTimingConfig.vue";
import ViMeasureConfig from "@/views/configs/deviceConfig/component/viMeasureConfig.vue";
import { storeToRefs } from "pinia";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useRoute } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { useLogic } from "@/views/system/user/logic/logic";
import { getProductListApi } from "@/api/products/product";
import { getDeviceGroupOptionsApi } from "@/api/products/deviceGroup";
import { handleTree } from "@/utils/tree";
import { getDeviceOptionsApi } from "@/api/products/device";
import { Grid } from "@element-plus/icons-vue";
import { destroyMqttConnection, getWebTopic, subscribeTopic, WebsiteMessage } from "@/utils/appCommon/mqttConnect";
import { ElNotification } from 'element-plus'
import { useI18n } from "vue-i18n";
import {
  ProductKeyM1,
  ProductKeyM1V1, ProductKeyM1V2,
  ProductKeyM2, ProductKeyM2V1, ProductKeyM2V2,
  ProductKeyMCM1,
  ProductKeyVI1,
  ProductKeyVI2
} from "@/consts/product";



const {t} = useI18n();

const pageSizeOps = ref(pageSizeOptions)
const route = useRoute();
const storeInfo = useUserStore()
const {deptId}= storeToRefs(storeInfo)

const RouteName = "device-config";
defineOptions({
  name: RouteName,
});
const forceRefresh = ref(0);
// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  deptId: deptId.value,  //初始部门id
  deviceNos:[],
  productId: 0,
  productKey: "",
  deviceGroupId: undefined,
});

const selected = ref(0);
const columnCount = ref(1);

function tabClick({ index }) {
  selected.value = index;
}

let productList = [];
const productOptions = ref([]);
const deviceGroupOptions = ref([]);
const {deptTreeList,getDeptTree}  = useLogic()
const deviceNoOptions = ref([])

watch(() => route.query, (newVal) => {
  console.log(route)
  if(route.name == RouteName && newVal){
    if (route.query.deviceNo && route.query.deviceNo != "") {
      searchParams.value.deviceNos = [route.query.deviceNo.toString()]
    }
    if (route.query.deptId && Number(route.query.deptId)>0) {
      searchParams.value.deptId = Number(route.query.deptId);
    }
    if (route.query.productId && Number(route.query.productId)>0) {
      searchParams.value.productId = Number(route.query.productId);
      searchParams.value.productKey = productList.find(item => item.id === route.query.productId)?.productKey || '';
    }
    setTimeout(async ()=>{
      await reLoadThisPageData()
      await handleSearch(searchParams.value)
    },50)
  }
}, { immediate: true ,deep:true});
onMounted(async () => {
  await getDeptTree()
  const productOptionsRes = await getProductListApi({
    pageSize:500,
    page:1,
    wheres:{
      openStatus:1,
    },
  })
  if(productOptionsRes.code == 0){
    productList = productOptionsRes.data.list ? productOptionsRes.data.list : [];
    productOptions.value = [
      ...productOptionsRes.data.list.map(option => ({
        val: option.id,
        label: option.name
      }))
    ];
  }
  await reLoadThisPageData()
})

const loading = ref(false);
const reLoadThisPageData =async ()=>{
  await reLoadDeviceGroups()
  await reLoadDevices()
}

const reLoadDeviceGroups = async ()=>{
  const req = new Map;
  if(searchParams.value.deptId){
    req.deptId = searchParams.value.deptId;
  }
  const deviceGroupOptionsRes = await getDeviceGroupOptionsApi(req)
  if(deviceGroupOptionsRes.code == 0){
    deviceGroupOptions.value = handleTree(deviceGroupOptionsRes.data.options);
    console.log(toRaw(deviceGroupOptions.value))
  }
}

const reLoadDevices = async ()=>{
  const req = {
    fieldKey:"deviceNo",
    fieldLabel:"name",
  };
  if(searchParams.value.deptId){
    req.deptId = searchParams.value.deptId;
  }
  if(searchParams.value.productId){
    req.productId = searchParams.value.productId;
  }
  if(searchParams.value.deviceGroupId){
    req.deviceGroupId = searchParams.value.deviceGroupId;
  }
  deviceNoOptions.value = [];
  const deviceOptionsRes = await getDeviceOptionsApi(req)
  if(deviceOptionsRes.code == 0){
    deviceNoOptions.value = deviceOptionsRes.data.options;
  }
}

const listComponents = computed(() => {
   let result = [];
   if(searchParams.value.productKey == ProductKeyM1 || searchParams.value.productKey == ProductKeyM2){
     result = [
       { key: "AeParamConfig", title: "AE-"+t('device.configTitles.samplingConfig'), component: AeParamConfig },
       { key: "AefirConfig", title: "AE-"+t('device.configTitles.firConfig'), component: AefirConfig },
       { key: "AeTimingConfig", title: t('device.configTitles.timingConfig'), component: AeTimingConfig },
       { key: "AefftConfig", title:  t('device.configTitles.fftConfig'), component: AefftConfig },
       { key: "AeLevelConfig", title: t('device.configTitles.ratingConfig'), component: AeLevelConfig },
       { key: "Aefrp", title: t('device.configTitles.frpConfig'), component: Aefrp },
     ]
   }else if(searchParams.value.productKey == ProductKeyVI1 || searchParams.value.productKey == ProductKeyVI2){
     result = [
       { key: "ViMeasureConfig", title: "VI-"+t('device.configTitles.samplingConfig'), component: ViMeasureConfig },
       { key: "AeTimingConfig", title:  t('device.configTitles.timingConfig'), component: AeTimingConfig },
     ]
   }else if(searchParams.value.productKey == ProductKeyM1V1 ||
     searchParams.value.productKey == ProductKeyM1V2 ||
     searchParams.value.productKey == ProductKeyM2V1 ||
     searchParams.value.productKey == ProductKeyM2V2 ){
     result = [
       { key: "AeParamConfig", title: "AE-"+t('device.configTitles.samplingConfig'), component: AeParamConfig },
       { key: "AefirConfig", title: "AE-"+t('device.configTitles.firConfig'), component: AefirConfig },
       { key: "ViMeasureConfig", title: "VI-"+t('device.configTitles.samplingConfig'), component: ViMeasureConfig },
       { key: "AeTimingConfig", title: t('device.configTitles.timingConfig'), component: AeTimingConfig },
       { key: "AefftConfig", title: t('device.configTitles.fftConfig'), component: AefftConfig },
       { key: "AeLevelConfig", title: t('device.configTitles.ratingConfig'), component: AeLevelConfig },
       { key: "Aefrp", title: t('device.configTitles.frpConfig'), component: Aefrp },
     ]
   }else if(searchParams.value.productKey == ProductKeyMCM1){
     result = [
       { key: "Aefrp", title: t('device.configTitles.frpConfig'), component: Aefrp },
     ]
   }
   return result;
});


const searchFields = ref(  [
  { prop: "productId",
    name: t("products.devicePage.productId"),
    type: "select",
    clearable: false,
    isHidden: false,
    formOptions:productOptions
  },
  { prop: "deviceNos",
    name: t("products.devicePage.deviceNo"),
    type: "multiSelect",
    clearable: true,
    isHidden: false,
    formOptions:deviceNoOptions
  },
  {
    prop: 'deptId',
    name:  t("products.devicePage.deptId"),
    type: 'cascader',
    cascaderOptions: deptTreeList,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: 'deviceGroupId',
    name:  t("products.devicePage.groupId"),
    type: 'cascader',
    cascaderOptions: deviceGroupOptions,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
])

const handleChange = (e: any) => {
  console.log(e)
  if(e.productId != searchParams.value.productId){
    searchParams.value.productId = e.productId
    searchParams.value.deviceNos = []
    searchParams.value.productKey = productList.find(item => item.id === e.productId)?.productKey || '';
    reLoadDevices()
  }
  if(e.deptId != searchParams.value.deptId){
    searchParams.value.deptId = e.deptId
    reLoadDeviceGroups()
    reLoadDevices()
  }
  if(e.deviceGroupId != searchParams.value.deviceGroupId){
    searchParams.value.deviceGroupId = e.deviceGroupId
    reLoadDevices()
  }
}

let hasSubTopic = false

const handleSearch = async (e:any) => {
  console.log(e)
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  searchParams.value.productKey = productList.find(item => item.id === searchParams.value.productId)?.productKey || '';
  console.log(toRaw(searchParams.value))

  forceRefresh.value = Math.random()

  await doSubTopic();
}

const handleConfigSubmit = (e:any) => {
  forceRefresh.value = Math.random()
}

const doSubTopic = async () =>{
  if(!hasSubTopic){
    return
  }
  hasSubTopic = true;
  const topic = getWebTopic(searchParams.value.deptId)
  // 订阅主题并处理消息
  await subscribeTopic(topic, (topic, message, packet) => {
    console.log(`收到来自${topic}的消息:`, message.toString());
    try {
      const messageStr = message.toString();
      const parsedMessage = JSON.parse(messageStr) as WebsiteMessage;
      const msgtype =  parsedMessage.status>0? 'Warning':'success'
      if(parsedMessage.bigType == "operate"){
        forceRefresh.value = Math.random()
        //@ts-ignore
        ElNotification({
          title: t('buttons.tips.operationResult'),
          message:parsedMessage.type + " ok",
          type: msgtype,
        })
      }
    } catch (error) {
      console.warn(`无法解析消息为WebsiteMessage格式:`, error);
    }
  });
}

onUnmounted(async ()=>{
  destroyMqttConnection()
})

const handleReset = (e:any) => {
  console.log(e)
}

// 对话框相关状态
const commandsDialogVisible = ref(false);
const currentDeviceNo = ref('');

// 打开功能区对话框
const openCommandsDialog = (deviceNo: string) => {
  currentDeviceNo.value = deviceNo;
  commandsDialogVisible.value = true;
};

</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=3
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
        <div style="margin: 5px 10px 0px 10px">
          <!-- 列数选择改为下拉菜单 -->
          <el-dropdown class="dropdown-control" trigger="click">
            <span class="el-dropdown-link">
              <el-button type="primary" size="small" :icon="Grid">
                {{ columnCount }}{{t('buttons.columns')}}
              </el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="columnCount = 1">1{{t('buttons.columns')}}</el-dropdown-item>
                <el-dropdown-item @click="columnCount = 2">2{{t('buttons.columns')}}</el-dropdown-item>
                <el-dropdown-item @click="columnCount = 3">3{{t('buttons.columns')}}</el-dropdown-item>
                <el-dropdown-item @click="columnCount = 4">4{{t('buttons.columns')}}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </template>

    <div v-if="searchParams.deviceNos && searchParams.deviceNos.length > 0" class="device-config-grid" :style="{ gridTemplateColumns: `repeat(${columnCount}, 1fr)` }">
      <div v-for="deviceNo in searchParams.deviceNos" :key="deviceNo" class="device-config-item">
        <div class="device-header">
          <h3>{{ deviceNo }}
            <el-button type="primary" size="small" @click="openCommandsDialog(deviceNo)" style="margin-left: 10px">
            {{t('device.commands.functions')}}
          </el-button> </h3>

        </div>
        <el-tabs @tab-click="tabClick" v-model="selected" :tab-position="'left'" :stretch="true">
          <template v-for="(item, index) of listComponents" :key="item.key">
            <el-tab-pane :label="item.title" :name="index" :lazy="true">
              <keep-alive>
                <component
                  :is="item.component"
                  :key="`${item.key}-${deviceNo}`"
                  :deviceNo="deviceNo"
                  :deviceOptions="deviceNoOptions"
                  :params="searchParams"
                  :forceRefresh="forceRefresh"
                  @onsubmit="handleConfigSubmit"
                  />
              </keep-alive>
            </el-tab-pane>
          </template>
        </el-tabs>
  </div>
</div>
<div v-else class="no-device">
  <el-empty :description="t('device.tips.pickDeviceFirst')" />
</div>

<!-- 功能区对话框 -->
<el-dialog
  v-model="commandsDialogVisible"
  :title="t('device.commands.functions')"
  width="600px"
  draggable
  :close-on-click-modal="false"
  destroy-on-close
>
  <aeCommands :device-no="currentDeviceNo" :params="searchParams"/>
</el-dialog>
</el-card>
</template>

<style scoped lang="scss">
.device-config-grid {
  display: grid;
  gap: 20px;
  margin-top: 20px;
}

.device-config-item {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
}

.device-header {
  padding: 12px 20px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }
}

.no-device {
  padding: 40px 0;
  text-align: center;
}
</style>





